import { defineComponent, h, onMounted, ref, watch } from 'vue';
import * as echarts from 'echarts';

export const EChart = defineComponent({
    name: 'EChart',
    components: {
    },
    inheritAttrs: true,
    props: {
        width: { type: Number, required: true, default: 500 },
        height: { type: Number, required: true, default: 300 },
        option: {
            type: Object,
            default: () => {
                return {};
            }
        },
        title: { type: Object },
        xAxis: { type: Object },
        yAxis: { type: Object },
        series: { type: Array, required: true },
    },
    setup(props) {
        const chartDom = ref<HTMLDivElement>();
        let myChart: echarts.ECharts;
        onMounted(() => {
            setTimeout(() => {
                myChart = echarts.init(chartDom.value, null, {
                    renderer: 'svg'
                });
                const option = props.option;
                option.xAxis = props.xAxis;
                option.yAxis = props.yAxis;
                option.series = props.series;
                myChart.setOption(option);

            }, 1000)
        });

        watch(props, () => {
            const option = props.option;
            option.title = props.title;
            option.xAxis = props.xAxis;
            option.yAxis = props.yAxis;
            option.series = props.series;
            myChart.setOption(option);

        });

        watch(() => [props.width, props.height], () => {
            myChart.clear();
            myChart.resize({
                width: props.width,
                height: props.height
            });
        });

        return {
            chartDom,
        };
    },

    render() {
        return h(
            'div',
            {
                ref: "chartDom",
                style: {
                    width: this.$props.width + 'px',
                    height: this.$props.height + 'px',
                },
            },
        );
    },
});
